package se.his.assignment1.client;

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: djurczak
 * Date: Jan 23, 2009
 * Time: 1:22:31 PM
 * To change this template use File | Settings | File Templates.
 */


import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

class UDPChatclient extends JFrame implements ActionListener {
    // This class should be sufficiently complete, although
    // you are allowed to change it if you wish.

    private final JTextField m_chatInput;
    private final JTextArea m_chatOutput;

    public UDPChatclient(ActionListener listener, String userName) {
        setSize(700, 500);
        setTitle("Chat client for " + userName);

        m_chatOutput = new JTextArea(10, 15);
        m_chatInput = new JTextField(20);

        m_chatOutput.setWrapStyleWord(true);
        m_chatOutput.setLineWrap(true);
        m_chatOutput.setEditable(false);
        m_chatOutput.setBackground(Color.BLACK);
        m_chatOutput.setForeground(Color.GREEN);

        Container pane = getContentPane();
        pane.add(m_chatOutput, BorderLayout.NORTH);
        pane.add(m_chatInput, BorderLayout.SOUTH);
        pane.add(new JScrollPane(m_chatOutput), BorderLayout.CENTER);

        m_chatInput.addActionListener(listener);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void displayMessage(String message) {
        m_chatOutput.append(message + "\n");
    }

    public String getInput() {
        return m_chatInput.getText();
    }

    public void clearInput() {
        m_chatInput.setText("");
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
    }
}

class ServerConnection {

    private DatagramSocket m_socket = null;
    private InetAddress m_serverAddress = null;
    private int m_serverPort = -1;

    private String m_name;

    public ServerConnection(String hostName, int port) {
        m_serverPort = port;

        // * get address of host based on parameters and assign it to m_serverAddress
        try {
            m_serverAddress = InetAddress.getByName(hostName);
        } catch (UnknownHostException ex) {
            System.err.println("Error: unable to find server address for " + hostName);
            System.exit(-1);
        }

        // * set up socket and assign it to m_socket
        try {
            m_socket = new DatagramSocket();
            m_socket.connect(m_serverAddress, m_serverPort);
        } catch (SocketException ex) {
            System.err.println("Unable to create socket");
            System.exit(-1);
        }
    }

    public boolean handshake(String name) {

        byte[] buf2 = new byte[256];
        DatagramPacket p = new DatagramPacket(buf2, buf2.length);

        m_name = name;

        //Create the message
        String msg = "ConnectionRequest;" + name;
        // * marshal connection message containing user name
        byte[] buf = msg.getBytes();
        try {
            // * send message via socket
            m_socket.send(new DatagramPacket(buf, buf.length));

            // * receive response message from server
            m_socket.receive(p);

            // * unmarshal response message to determine whether connection was successful
            msg = new String(p.getData(), p.getOffset(), p.getLength());
        } catch (IOException ex) {
            System.err.println("Unable to send connection packet");
            System.exit(-1);
        }

        // * return false if connection failed (e.g., if user name was taken)
        return msg.equals("success");
    }

    public String receiveChatMessage() {
        byte[] buf = new byte[256];
        DatagramPacket p = new DatagramPacket(buf, buf.length);


        String msg;
        try {
            // * receive message from server
            m_socket.receive(p);

        } catch (IOException ex) {
            System.err.println("Error receiving chat message");
            System.exit(-1);
        }

        // * unmarshal message if necessary
        msg = new String(p.getData(), p.getOffset(), p.getLength());

        // Update to return message contents
        String[] contents = msg.split(";");

        if(contents.length>2){
            msg = "<"+ contents[0] +" tells you>:";
        }
        else {
            msg = contents[0] + ":";
        }

        msg = msg + contents[1];

        return msg;
        // todo: adjust display of message
    }

    public void sendChatMessage(String message) {
        //Create the message
        String msg = "ChatMessage;" + m_name + ";" + message;
        // * marshal connection message containing user name
        byte[] buf = msg.getBytes();

        try {
            // * send a chat message to the server
            m_socket.send(new DatagramPacket(buf, buf.length));

        } catch (IOException ex) {
            System.err.println("Unable to send chat message");
            System.exit(-1);
        }
    }
}


